﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TerrainManager : MonoBehaviour
{
    public static TerrainManager Instance
    {
        get
        {
            if (_Instance == null)
            {
                _Instance = FindObjectOfType<TerrainManager>();
            }
            if (!_Instance)
            {
                GameObject obj = new GameObject("TerrainManager");
                _Instance = obj.AddComponent<TerrainManager>();
            }
            return _Instance;
        }
        set
        {
            _Instance = value;
        }
    }
    private static TerrainManager _Instance;

    private List<GameObject> terrainList = new List<GameObject>();

    [System.Serializable]
    public struct TerrainInfo
    {
        public TerrainType type;
        public GameObject prefab;
    }

    [SerializeField]
    public TerrainInfo[] terrainPrefabs;
    Dictionary<TerrainType, TerrainInfo> terrainDict = new Dictionary<TerrainType, TerrainInfo>();
    //Dictionary<TerrainType, GameObject> terrainPrefabDict = new Dictionary<TerrainType, GameObject>();

    // Start is called before the first frame update
    void Awake()
    {
        foreach (TerrainInfo info in terrainPrefabs)
        {

            if (!terrainDict.ContainsKey(info.type))
            {
                terrainDict[info.type] = info;
            }
        }
    }

    public GameObject CreateTerrain(TerrainType type)
    {
        if (terrainDict.ContainsKey(type))
        {
            GameObject obj = Instantiate(terrainDict[type].prefab, Vector3.zero, Quaternion.identity);
            terrainList.Add(obj);
            return obj;
        }
        else return null;
    }

    public bool HasTerrain(GameObject obj)
    {
        return terrainList.Contains(obj);
    }

    public bool DestroyTerrain(GameObject obj)
    {
        if (terrainList.Remove(obj))
        {
            Vector3 position = obj.transform.position;
            position.z = -3;
            GameObject particleObject = EffectObjectManager.Instance.CreateEffectObject("Prefabs/Effect/StoneParticle", position);
            Destroy(obj);
        }
        return true;
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
